#include "buffer.h"

#include "netlib.h"

namespace {

std::string ReadBuffer(net::IBuffer* buffer, uint32_t len) {
    int size = len > buffer->GetSize() ? 1024 * 10 + 1 : len + 1;
    char* buf = new char[size];
    std::string s;
    while (buffer->GetSize() > 0 && len > 0) {
        int ret = buffer->Read(buf, size - 1);
        buf[ret] = 0;
        len -= ret;
        s.append(buf);
    }

    delete[] buf;
    buf = NULL;
    return s; 
}

}

namespace kxlua {

Buffer::Buffer(NetLib* lib) {
    lib_ = lib;
    name_ = "Buffer";
    isOpen_ = false;
}

Buffer::~Buffer() {
}

const std::string& Buffer::GetName() const {
    return name_;
}

bool Buffer::Open() {
    if (!isOpen_) {
        luabind::module(lib_->GetLua().GetState()) 
        [
            luabind::def("ReadBuffer", ReadBuffer),

            luabind::class_<net::IBuffer>("Buffer")
            .def("Clean", &net::IBuffer::Clean)
            .def("Hold", &net::IBuffer::Hold)
            .def("Revert", &net::IBuffer::Revert)
            .def("Commit", &net::IBuffer::Commit)
            .def("GetSize", &net::IBuffer::GetSize)
            .def("Read", &net::IBuffer::Read)
            .def("Write", &net::IBuffer::Write)
        ];
        isOpen_ = true;
    }
    return true;
}

bool Buffer::Close() {
}

}
